package com.xuebusi.service;

import com.xuebusi.common.util.FileUtil;
import com.xuebusi.common.ResultModel;
import com.xuebusi.entity.Img;
import com.xuebusi.entity.ImgExample;
import com.xuebusi.mapper.ImgMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

@Service
public class ImgService {

    @Value("${image.server.host}")
    private String imgSevHost;

    @Autowired
    private ImgMapper imgMapper;

    /**
     * 上传图片
     *
     * @Author shiyanjun
     * @Date 2018/9/23 下午9:08
     * @Param
     * @Return
     * @Exception
     */
    public ResultModel<List<Img>> upload(MultipartHttpServletRequest request, String name) {
        ResultModel<List<Img>> resultModel = new ResultModel<>();
        resultModel.fail();

        List<MultipartFile> files = request.getFiles(name);
        if (files.isEmpty()) {
            resultModel.setMessage("文件不能为空");
            return resultModel;
        }

        List<Img> imgList = new ArrayList<>();

        try {
            String imgDir = FileUtil.getFileDir();
            File path = new File(imgDir);
            if (!StringUtils.isEmpty(imgDir)) {
                if (!path.exists()) {
                    path.mkdirs();
                }
            }

            for (MultipartFile file : files) {
                String imgKey = FileUtil.genFileKey();
                String newName = FileUtil.getNewName(file, imgKey);
                String filePath = imgDir + newName;

                Img img = new Img();
                img.setImgName(newName);
                img.setImgKey(imgKey);
                String sutPath = imgDir.substring(imgDir.indexOf("img"));
                img.setImgPath(imgSevHost + sutPath + FileUtil.getNewName(file, imgKey));

                imgMapper.insert(img);
                imgList.add(img);

                File newFile = new File(filePath);
                FileOutputStream out = new FileOutputStream(newFile);
                BufferedOutputStream buffer = new BufferedOutputStream(out);
                buffer.write(file.getBytes());
                buffer.flush();
                buffer.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return resultModel;
        }
        resultModel.success(imgList);
        return resultModel;
    }

    public List<Img> selectByExample(ImgExample imgExample) {
        return imgMapper.selectByExample(imgExample);
    }
}
